package com.shujia.flink.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend
import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer, FlinkKafkaProducer}

object Demo5ExacttlyOnce {

  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 开启在 job 中止后仍然保留的 externalized checkpoints
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    //RocksDb
    val stateBackend: StateBackend = new RocksDBStateBackend("hdfs://master:9000/data/flink_checkpoint", true)

    env.setStateBackend(stateBackend)


    /**
      * 数据消费的唯一一次：通过checkpoint保证
      *
      */


    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092")
    properties.setProperty("group.id", "test")

    //创建消费者
    val flinkKafkaConsumer = new FlinkKafkaConsumer[String](
      "source",
      new SimpleStringSchema(),
      properties)

    flinkKafkaConsumer.setStartFromEarliest() // 尽可能从最早的记录开始


    //使用kafka source
    val kafkaDS: DataStream[String] = env.addSource(flinkKafkaConsumer)


    /**
      * 数据sink端保证唯一一次： 通过两步提交的sinkFunction
      * 1、在checkpoint开始的时候开启kafka的事务
      * 2、在checkpoint完成之后提交kafka事务
      *
      */

    val properties1 = new Properties
    properties1.setProperty("bootstrap.servers", "master:9092")

    //事务的超时时间
    properties1.setProperty("transaction.timeout.ms", 5 * 60 * 1000 + "")

    //创建生产者
    val myProducer = new FlinkKafkaProducer[String](
      "sink", // 目标 topic
      new SimpleStringSchema,
      properties1,
      null, //分区方法
      Semantic.EXACTLY_ONCE, // 唯一一次
      5
    ) // 序列化 schema

    //将数据发送到kafka 中
    kafkaDS.addSink(myProducer)

    env.execute()

    /**
      *
      * kafka-console-consumer.sh --bootstrap-server  master:9092  --from-beginning --isolation-level read_committed  --topic sink
      *
      */

  }

}
